package com.tanhua.mongo.api;

import com.tanhua.api.UserLikeApi;
import com.tanhua.model.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@DubboService
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存喜欢/不喜欢数据
    @Override
    public boolean save(Long userId, Long likeUserId, boolean isLike) {
        try {
            //封装查询条件
            Query query = Query.query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));

            //判断数据是否存在
            if (mongoTemplate.exists(query, UserLike.class)) {
                //存在 修改
                Update update = Update.update("isLike", isLike);
                mongoTemplate.updateFirst(query, update, UserLike.class);
            } else {
                //不存在 新增
                UserLike userLike = new UserLike();
                userLike.setUserId(userId);
                userLike.setLikeUserId(likeUserId);
                userLike.setIsLike(isLike);
                userLike.setCreated(System.currentTimeMillis());
                userLike.setUpdated(System.currentTimeMillis());

                mongoTemplate.save(userLike);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 互相喜欢，喜欢，粉丝 - 统计
     *
     * @param userId
     * @return
     */
    @Override
    public Map<String, Integer> selectByUserId(Long userId, Boolean falg) {
        Map<String,Integer> map = new HashMap<>();
        //查询条件
        Query query = Query.query(Criteria.where("userId").is(userId).and("isLike").is(falg));
        //查询我喜欢的人数
        long loveCount = mongoTemplate.count(query,UserLike.class);

        Query query1 = Query.query(Criteria.where("likeUserId").is(userId).and("isLike").is(falg));
        //查询喜欢我的人数
        long fanCount = mongoTemplate.count(query1, UserLike.class);

        //查询互相喜欢
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);

        for (UserLike userLike : userLikes) {
            Long likeUserId = userLike.getLikeUserId();
            Query query2 = Query.query(Criteria.where("likeUserId").is(likeUserId).and("isLike").is(falg));

            long eachLoveCount = mongoTemplate.count(query2, UserLike.class);
            map.put("eachLoveCount", (int) eachLoveCount);
        }
        map.put("loveCount", (int) loveCount);
        map.put("fanCount", (int) fanCount);

        return map;
    }
}
